const api = require('../../utils/utils')
var app = getApp()
Page({
  data: {
    iconUrl: api.iconUrl,
    // 导航数据
    list: [{
        pagePath: "/pages/index/index",
        text: "首页",
        iconPath: api.iconUrl + "home.png",
        selectedIconPath: api.iconUrl + "home-filling.png"
      },
      {
        pagePath: "/pages/my/my",
        text: "我的",
        iconPath: api.iconUrl + "user.png",
        selectedIconPath: api.iconUrl + "user-filling.png"
      }
    ],
    // 确认登录对话框
    login_dialog_show: false,
    loading_show: false,
    // 患者列表数据
    patients: [],
  },
  onLoad: function (options) {
    this.setData({
      loading_show: true
    })
    api.checklogin().then((res) => {
        app.globalData.isLogin = true
        this.getPatients()
      })
      .catch((err) => {
        app.globalData.isLogin = false
        this.setData({
          login_dialog_show: true
        })
      })
  },
  onShow: function () {
    if (app.globalData.isLogin == false) {
      this.setData({
        patients: [],
        loading_show: false,
      })
    } else {
      this.getPatients()
    }
  },
  // 跳转到登录页面
  toLogin() {
    wx.navigateTo({
      url: '/pages/login/login',
    })
  },
  // 搜索框点击完成按钮时触发
  confirmSearch(event) {
    // 清空列表
    this.setData({
      patients: []
    })
    // 获取患者数据
    this.getPatients(event.detail.value)
  },
  // 获取患者列表
  getPatients(params='') {
    let url = '/users/query/';
    if (params != "") {
      if (this.re_phone(params)) url = url + '?username=' + params;
      else url = url + '?realname__contains=' + params;
    }
    api.request('get', url).then(res => {
      this.setData({
        patients: res.results
      })
    }).catch(err => {
      console.log(err);
    })
  },
  // 判断是否为手机号的正则表达式
  re_phone(phones) {
    var myreg = /^[1][3,4,5,7,8,9][0-9]{9}$/;
    if (!myreg.test(phones)) {
      // console.log('手机号格式不正确')
      return false;
    } else {
      // console.log('手机号格式正确')
      return true;
    }
  },
  // 跳转到患者个人页面
  toLabel(details) {
    wx.navigateTo({
      url: `/pages/label/index?patient_id=${details.currentTarget.id}`,
    })
  },
  // 跳转到患者个人页面
  toRecord(details) {
    wx.navigateTo({
      url: `/pages/record/record?patient_id=${details.currentTarget.id}`,
    })
  }
})